/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.garagesale.admin.action;

import com.garagesale.config.hibernate.HibernateUtil;
import com.garagesale.data.DBAccess;

import com.garagesale.data.Administrator;
import com.garagesale.data.User;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;

/**
 *
 * @author stolworthyfamily
 */
public class CreateAdminAction extends org.apache.struts.action.Action
{

    /* forward name="success" path="" */
    private static final String SUCCESS = "welcome";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {

        DBAccess dbAccess = DBAccess.getInstance();
        String add = request.getParameter("sub");
        String delete = request.getParameter("userID");
        String adminName = request.getParameter("username");
        String AdminPassword = request.getParameter("password");
        String adminEmail = request.getParameter("emailAddress");

        if (delete != null && !delete.isEmpty())
        {
            Integer adminId = Integer.parseInt(delete);

            User foundUser = DBAccess.getInstance().retrieveByID(User.class, adminId);

            if (foundUser != null)
            {
                dbAccess.delete(foundUser);
            }

        }

        if (add != null && !add.isEmpty())
        {

            User user = new User(adminName, adminName, adminName, AdminPassword);
            user.setEmailAddress(adminEmail);
            user.setUserRole("admin");

            dbAccess.create(user);
        }

        List<User> admin = dbAccess.retrieveAllAdmins();


        request.setAttribute("admin", admin);



        return mapping.findForward(SUCCESS);
    }
}
